import BothSide from "../../BothSide";
import { PropType, defineComponent, watchEffect } from "vue";
import Checkbox from "../Checkbox";
import Input from "../Input";
import ListItem from "./ListItem";
import { FeatherSearch } from "cui-vue-icons/feather";

export type TransferListProps = {
    width?: number,
    height?: number,
    store?: any,
    name?: string,
    value?: any[],
    title?: string,
    render?: (item: any) => any,
    filter?: boolean
}


export default defineComponent({
    name: 'TransferList',
    props: {
        width: {type: Number as PropType<TransferListProps['width']>},
        height: {type: Number as PropType<TransferListProps['height']>},
        store: {type: Object as PropType<TransferListProps['store']>},
        name: {type: String as PropType<TransferListProps['name']>},
        value: {type: Array as PropType<TransferListProps['value']>},
        title: {type: String as PropType<TransferListProps['title']>},
        render: {type: Function as PropType<TransferListProps['render']>},
        filter: {type: Boolean as PropType<TransferListProps['filter']>}
    },
    emits: ['select'],
    setup (props: TransferListProps, { emit }) {
        const style = () => ({
            width: props.width ? `${props.width}px` : '',
            height: props.height ? `${props.height}px` : '',
        });

        const title = props.title ?? (props.name === 'source' ? '源列表' : '目标列表');

        const data = () => {
            const v = props.value || [];
            const map: any = {};
            v.forEach((vv: any) => {
                map[vv] = true;
            });
            return props.store.data.filter((item: any) => {
                if (props.name === 'source') {
                    return !map[item.id];
                } else {
                    return map[item.id];
                }
            });
        };

        const validLength = () => {
            let length = 0;
            data().forEach((item: any) => {
                if (!item.disabled) {
                    length++;
                }
            });
            return length;
        };

        const onSelect = (data: any) => {
            emit('select', data, !data._checked);
            if (data._checked) {
                props.store[`${props.name}Ids`] = [...props.store[`${props.name}Ids`], data.id];
            } else {
                const arr = props.store[`${props.name}Ids`];
                arr.splice(arr.indexOf(data.id), 1);
                props.store[`${props.name}Ids`] = arr;
            }
        };

        const isCheckedAll = () => {
            const arr = props.store[`${props.name}Ids`];
            if (arr.length > 0) {
                if (validLength() === arr.length) {
                    return true;
                } else {
                    return 'indeterminate';
                }
            } else {
                return false;
            }
        };

        const onCheckedAll = (checked: boolean) => {
            const ids: any[] = [];
            const items = data();
            items.forEach((item: any) => {
                emit('select', item, checked);
            });
            items.forEach((item: any) => {
                if (item._checked) {
                    ids.push(item.id);
                }
            });
            props.store[`${props.name}Ids`] = ids;
        };

        watchEffect(() => {
            const arr = props.store[`${props.name}Ids`];
            if (arr.length) {
                props.store[`${props.name}Disabled`] = false;
            } else {
                props.store[`${props.name}Disabled`] = true;
            }
        });

        // 过滤
        const onFilter = (v: any) => {
            const arr = data();
            arr.forEach((item: any) => {
                const text = () => {
                    if (props.render) {
                        return props.render(item);
                    }
                    return item.title;
                };
                const findAItem = props.store.data.find((aitem) => {
                    return aitem.id === item.id;
                });
                if (findAItem) {
                    findAItem._hide = !text().includes(v);
                }
            });
        };

        const count = () => data().length;
        const countInfo = () => {
            const arr = props.store[`${props.name}Ids`];
            return arr.length ? arr.length + '/' + count() : count();
        };

        return () => <div class="cm-transfer-list" style={style()}>
            <div class="cm-transfer-list-header">
                <BothSide>
                    <div>
                        <Checkbox modelValue={isCheckedAll()} onChange={onCheckedAll}/>
                        <span>{title}</span>
                    </div>
                    <div class="">{countInfo()}</div>
                </BothSide>
            </div>
            <div class="cm-transfer-list-body">
                {
                    props.filter
                        ? <div class="cm-transfer-filter-wrap">
                            <Input append={<FeatherSearch/>} size="small" onInput={onFilter}/>
                        </div>
                        : null
                }
                <div class="cm-transfer-list-content">
                    {
                        data().map(item => {
                            return <ListItem data={item} onSelect={onSelect} render={props.render}/>;
                        })
                    }
                </div>
            </div>
        </div>;
    }
});
